﻿namespace LogManager.Core.Models.Smtp
{
    using LogManager.Core.Infrastructure.Logging;
    using LogManager.Utils.Unity;
    using LogManager.Utils.Xml;
    using System;
    using System.ComponentModel;
    using System.Linq;
    using System.Net.Mail;
    using System.Xml.Linq;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class To : XmlElementBase, ITo
    {
        public const string DEFAULT_TEMPLATE = @"<To Addresses='sampleTo@domain.com,other@domain.fr' />";

        public string Addresses
        {
            get { return string.Join<string>(",", this.MailAddresses.Where(p => p.Value != null).Select(p => p.Value.Address)); }
        }
        public virtual BindingList<Email> MailAddresses { get; protected set; }

        /// <summary>
        /// Gets the
        /// </summary>
        //public List<MailAddress> MailAddresses
        //{
        //    get
        //    {
        //        if (string.IsNullOrEmpty(this.Addresses))
        //            return Enumerable.Empty<MailAddress>().ToList();

        //        var addresses = Addresses.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        //        return addresses.Select(p => new MailAddress(p)).ToList();
        //    }
        //}

        public To(XElement baseNode)
            : base(baseNode)
        {
            this.Initialize();
            this.PropertyChanged += (a, b) => SaveChanges();
            this.MailAddresses.ListChanged += (a, b) => SaveChanges();
        }

        private void Initialize()
        {
            var xml = new XmlResolver<To>(BaseNode);
            this.MailAddresses = ParseEmails(xml.GetAttributeValue(c => c.Addresses));
        }

        public override void SaveChanges()
        {
            var xml = new XmlResolver<To>(BaseNode);
            xml.SetAttributeValue(c => c.Addresses, Addresses);
        }

        private BindingList<Email> ParseEmails(string emailsString)
        {
            var mailAddresses = new BindingList<Email>();
            var emails = emailsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var email in emails)
            {
                try
                {
                    var mailAddr = new MailAddress(email);
                    mailAddresses.Add(mailAddr);
                }
                catch (Exception e)
                {
                    Log.Logger.AddWarning("Email parse error : " + email, e.Message);
                }
            }
            return mailAddresses;
        }
    }
}
